#include <bwio.h>
#include <user.h>
#include <ts7200.h>
#include <uart.h>
#include <io.h>
#include <vic.h>
#include <timer.h>
#include <defs.h>

void NameServer();
void TerminalRxServer();
void TerminalTxServer();
void ClockServer();
void TrainTxServer();
void TrainRxServer();
void IdleTask();

void Print1()
{
  bwprintf(COM1, "1\r\n");
}

void Print2()
{
  bwprintf(COM1, "2\r\n");
}

void Timer1Handler() {
  timer *const timer1 = (timer*)( TIMER1_BASE );
  vic *const vic2 = (vic*)( VIC1_BASE );
  timer1->clear = 0;
  vic2->vect_addr = 0;
  Print1();
}

void Timer2Handler() {  
  timer *const timer2 = (timer*)( TIMER2_BASE );
  vic *const vic2 = (vic*)( VIC1_BASE );
  timer2->clear = 0;
  vic2->vect_addr = 0;
  Print2();
}

void Clock1Init() {
  // init Timer3
  timer *const timer1 = (timer*)( TIMER1_BASE );
  timer1->load = 254000;
  timer1->control = ENABLE_MASK | MODE_MASK | CLKSEL_MASK;

  vic *const vic1 = (vic*)( VIC1_BASE );
  
  // install timer handler
  vic1->vect_addr0 = (int)( &Timer1Handler ) + CODE_BASE;  
  vic1->vect_cntl0 = 0x24;

  // init TC3OI
  vic1->int_select &= ~(0x10);
  vic1->int_enable |= 0x10;
}

void Clock2Init() {
  // init Timer3
  timer *const timer2 = (timer*)( TIMER2_BASE );
  timer2->load = 254000;
  timer2->control = ENABLE_MASK | MODE_MASK | CLKSEL_MASK;

  vic *const vic1 = (vic*)( VIC1_BASE );
  
  // install timer handler
  vic1->vect_addr2 = (int)( &Timer2Handler ) + CODE_BASE;
  vic1->vect_cntl2 = 0x25;

  // init TC3OI
  vic1->int_select &= ~(0x20);
  vic1->int_enable |= 0x20;
}

void UserInit() {
  Create( 8, &NameServer );
  Create( 8, &TerminalTxServer );
  // Create( 8, &TerminalRxServer );
  // Create( 8, &ClockServer );
  Create( 0, &IdleTask );

  Clock1Init();
  Clock2Init();
  
  
  for (;;) {
    Putc(COM2, 'A');
    Putc(COM2, '\r');
    Putc(COM2, '\n');
    Putc(COM2, '\0');
  }
}
